<!--
 * @Descripttion: 会计模板
 * @version: V1.0
 * @Author: GW
 * @Date: 2021-12-30 15:11:13
 * @LastEditors: GW
 * @LastEditTime: 2022-05-06 14:11:56
-->
<template>
    <div class="content-wrapper a-base-container">
        <div class="requisition-set-wrapper">
            <!--按钮-->
            <div class="btn-wrapper clearfix" style="margin-bottom:0px;">
                <a-row class="text-center clearfix">
                    <a-col :xs="24" :sm="24" :md="24" :lg="16" :xl="12">
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl">
                            <div class="btns" @click="templateEdit(1)">
                                <a-icon class="btns-icon" type="file-add" />
                                <div class="btns-text">新增</div>
                            </div>
                        </a-col>
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl">
                            <div class="btns" @click="templateEdit(2)">
                                <a-icon class="btns-icon" type="edit" />
                                <div class="btns-text">修改</div>
                            </div>
                        </a-col>
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl">
                            <div class="btns" @click="templateDelete">
                                <a-icon class="btns-icon" type="delete" />
                                <div class="btns-text">删除</div>
                            </div>
                        </a-col>
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl">
                            <div class="btns" @click="syncFun">
                                <a-icon class="btns-icon" type="file-sync" />
                                <div class="btns-text">刷新</div>
                            </div>
                        </a-col>
                    </a-col>
                </a-row>
            </div>
            <section class="content-demand-wrapper">
                <!--菜单-->
                <section class="content-menu" :style="menuStyle">
                    <!--收缩按钮-->
                    <div class="shrink-btn" @click="clickShrink">
                        <a-icon v-if="menuStyleStatus" class="" type="double-left" />
                        <a-icon v-else class="" type="double-right" />
                    </div>
                    <div class="menu-tree-box" :style="munuTreeStyle">
                        <a-tree :tree-data="treeMenu" show-icon default-expand-all @select="onSelect" :selected-keys="selectedTreeKeys">

                        </a-tree>
                    </div>
                </section>
                <section class="content-view">
                    <div class="template-list-box">
                        <a-table :scroll="{x:0,y:450}" :columns="columns" :data-source="dataSource" :row-selection="{ selectedRowKeys: selectedKeys, onChange: onSelectChange,columnWidth:40 }" :customRow="customClick" bordered :pagination="pagination" :loading="isRun">

                        </a-table>
                    </div>
                </section>
            </section>
        </div>
        <!-- modal 弹窗  -->
        <a-modal class="filed-table" :destroyOnClose="true" v-model="templateModal" title="模板" @cancel="cancel" width="1000px">
            <div class="finance-template-box-header">
                <div class="filter">
                    <div class="filter-label">模板编号:</div>
                    <div class="filter-control">
                        <a-input oninput="code=code.replace(/[^\d]/g,'')" v-model.trim="code"></a-input>
                    </div>
                </div>
                <div class="filter">
                    <div class="filter-label">模板名称:</div>
                    <div class="filter-control">
                        <a-input v-model.trim="templateName"></a-input>
                    </div>
                </div>
                <div class="filter">
                    <div class="filter-label"><span style="color:red">* </span>凭证字:</div>
                    <div class="filter-control">
                        <a-input read-only @click="searchGroup" v-model="word" autocomplete="off" placeholder="请选择凭证字"></a-input>
                        <searchGroupHeader ref="credentialsSearch" :inputValue="word" :componentName="'category'" @clickItem="searchBackData"></searchGroupHeader>
                    </div>
                </div>
                <div class="filter">
                    <div class="filter-label">是否默认:</div>
                    <div class="filter-control">
                        <a-select v-model="isDefault" style="width: 120px">
                            <a-select-option :value="1">是</a-select-option>
                            <a-select-option :value="0">否</a-select-option>
                        </a-select>
                    </div>
                </div>
                <div class="filter">
                    <div class="filter-label">描述:</div>
                    <div class="filter-control">
                        <a-input v-model.trim="remarks"></a-input>
                    </div>
                </div>
            </div>

            <a-table id="credentials_tb" class="atable-edit" style="min-height:200px;" :columns="columnsModal" :customRow="customClickModal" :data-source="dataSourceModal" :pagination="false" bordered>
                <template v-for="item in editColumn" :slot="item" slot-scope="text, record ,index">
                    <div>
                        <editable-cell v-if="isRouterAlive" :record="record" :col="item" :text="text" @showModalAuxiliary="showModalAuxiliary" @change="onCellChange(index, item, $event)" />
                    </div>
                </template>
            </a-table>
            <template slot="footer">
                <a-button type="primary" @click="templateSave">保存</a-button>
                <a-button @click="cancel" class="margin-left-10">关闭</a-button>
            </template>
            <div class="contextmenu-box">
                <!-- 右键菜单 -->
                <ul v-show="visible" :style="{left:left+'px',top:top+'px'}" class="contextmenu">
                    <li @click="handleAdd()">新增行</li>
                    <li @click="handleDelete()">删除行</li>
                    <!--<li @click="handleCopy()">复制行</li> -->
                </ul>
            </div>
        </a-modal>
    </div>
</template>

<script>

import { save, getList, remove, detail } from "@/api/finance/financeTemplate";
import editableCell from "@/views/finance/accounting/editTable/EditableCell";
import { components } from "@/utils/antTableComponents";
import searchGroupHeader from "@/components/PopUpLayer/searchGroupHeader";
import { mapState } from 'vuex';
import Sortable from 'sortablejs';

import { list as listNumberSet } from "@/api/erp/mumberSet";


export default {
    components: {
        editableCell,
        searchGroupHeader
    },
    data () {
        return {
            //----------↓样式----------
            btnGrid: {
                xs: 2,
                sm: 2,
                md: 2,
                lg: 2,
                xl: 2
            },
            //----------↑样式----------
            editColumn: [],
            nowId: null,
            treeMenu: [],
            menuStyle: {},
            munuTreeStyle: {},
            selectedTreeKeys: [],
            menuStyleStatus: true,
            voucherType: null,//选择单据类型
            voucherTypeName: null,
            visible: false,
            top: 0,
            left: 0,
            code: null,//模板编号
            templateName: null,//模板名称
            isDefault: 0,
            remarks: null,
            vclassId: null,
            vclassName: null,
            word: null,//凭证字
            dataSource: [],//列表数据
            isRun: false,
            dataSourceModal: [],
            columnsModal: [{
                title: "科目来源",
                dataIndex: "accountingType",
                width: 80,
                align: 'left',
                scopedSlots: { customRender: 'accountingType' },
            }, {
                title: "科目名称",
                dataIndex: "accountingName",
                width: 80,
                align: 'left',
                scopedSlots: { customRender: 'accountingName' },
            }, {
                title: "科目编码",
                dataIndex: "accountingCode",
                width: 80,
                align: 'left',
                // scopedSlots: { customRender: 'accountingCode' },
            }, {
                title: "借贷方向",
                dataIndex: "amountDirection",
                width: 80,
                align: 'left',
                scopedSlots: { customRender: 'amountDirection' },
            }, {
                title: "金额来源",
                dataIndex: "amountSource",
                width: 80,
                align: 'left',
                scopedSlots: { customRender: 'amountSource' },
            }, {
                title: "摘要",
                dataIndex: "remark",
                width: 80,
                align: 'left',
                scopedSlots: { customRender: 'remark' },
            }],
            columns: [{
                title: "序号",
                dataIndex: "index",
                key: "index",
                width: 40,
                align: 'center',
                customRender: (text, row, index) => {
                    return index + 1;
                }
            },
            {
                title: "模板编号",
                dataIndex: "code",
                key: "code",
                width: 120,
            },
            {
                title: "模板名称",
                dataIndex: "name",
                key: "name",
                width: 120,
            },
            {
                title: "凭证字",
                dataIndex: "word",
                key: "word",
                width: 120,
            },
            {
                title: "描述",
                dataIndex: "remarks",
                key: "remarks",
                width: 120,
            },
            {
                title: "单据类型",
                dataIndex: "voucherTypeName",
                key: "voucherTypeName",
                width: 120,
            },
            {
                title: "来源单据类型",
                dataIndex: "sourceVoucherType",
                key: "sourceVoucherType",
                width: 120,
            },
            {
                title: "状态",
                dataIndex: "status",
                key: "status",
                width: 60,
                customRender: (text, row, index) => {
                    return text == 0 ? '启用' : text == 1 ? '禁用' : '';
                }
            }, {
                title: "是否默认",
                dataIndex: "isDefault",
                key: "isDefault",
                width: 60,
                customRender: (text, row, index) => {
                    return text == 0 ? '否' : text == 1 ? '是' : '';
                }
            }, {
                title: "是否系统",
                dataIndex: "isSys",
                key: "isSys",
                width: 60,
                customRender: (text, row, index) => {
                    return text == 0 ? '否' : text == 1 ? '是' : '';
                }
            }],
            pagination: {
                //分页信息
                defaultPageSize: 20,
                current: 1,
                pageSize: 20,
                total: 0,
                size: 'small',
                showTotal: total => {
                    return (
                        <div>
                            共 {total} 条数据，每页
                            <a-input
                                style="height:22px !important;width:3.2rem;"
                                value={this.pagination.pageSize}
                                min={1}
                                max={500}
                                onPressEnter={e => this.changePageSize(e)}
                            />
                            条
                        </div>
                    );
                },
            },
            thisClickId: null,
            customClickModal: (record, index) => {
                return {
                    on: {
                        contextmenu: (e) => {//右键事件
                            e.preventDefault();
                            this.openMenu(e);
                            console.log('右键点击的', index);
                            this.thisClickId = index;
                        },
                    }
                }
            },
            customClick: (record, index) => {
                return {
                    on: { // 点击表事件
                        dblclick: (event) => {
                            this.selectedKeys = [record.id];
                            this.selectedRows = [record];
                            this.templateEdit(2);
                        },
                        click: (event) => { },// 点击行
                        contextmenu: (event) => { },
                        mouseenter: (event) => { },  // 鼠标移入行
                        mouseleave: (event) => { }
                    },
                };
            },
            mouseId: null,
            selectedKeys: [],
            selectedRows: [],
            numberReg: /^[1-9]{1}[0-9]*$/,
            floatReg: /^-?[0-9]*(\.[0-9]*)?$/,
            formData: [],
            templateModal: false,//凭证模板弹窗
            isRouterAlive: true,
        };
    },
    computed: {
        ...mapState({
            menusMap: state => state.user.menusMap,
            menus: state => state.user.menus,
        })
    },
    activated () {
        this.syncFun();
    },
    watch: {
        visible (value) {
            console.log('this is value', value)
            if (value) {
                document.body.addEventListener("click", this.closeMenu);
            } else {
                document.body.removeEventListener("click", this.closeMenu);
            }
        },
    },
    created () {
        this.components = components(this.columns);
        console.log(this.menus)

        this.editColumnArray();

        //获取单据类型列表
        this.getlistDesign();
    },
    methods: {
        reload () {
            //强制刷新表格
            this.isRouterAlive = false;
            this.$nextTick(function () {
                this.isRouterAlive = true;
            });
        },
        //补齐表格
        complementTable () {
            let length = this.dataSourceModal.length;
            if (this.dataSourceModal.length < 10) {
                let forlength = 10 - length;
                for (let i = 0; i < forlength; i++) {
                    let array = {};
                    this.dataSourceModal.push(array);
                }
            }
            this.$nextTick(() => {
                this.reload();
            })
        },
        openMenu (e) {
            //显示右键菜单
            var x = e.pageX - 250;
            var y = e.pageY - 40;
            this.top = y;
            this.left = x;
            this.visible = true;
        },
        closeMenu () {
            //隐藏右键菜单
            this.visible = false;
        },
        searchGroup () {
            this.$refs.credentialsSearch.showModal();
        },
        //获取单据类型列表
        getlistDesign () {
            let type = ['FV', 'MP', 'PU', 'SA', 'ST'];
            let request = { moduleCodes: type }
            listNumberSet(request).then(response => {
                if (response.code === 200) {
                    let map = new Map();
                    let data = response.data;
                    data.forEach(item => {
                        let { moduleName, voucherCode, name } = item;
                        let firstLevel = map.get(moduleName);
                        if (!firstLevel) {
                            firstLevel = new Object();
                            firstLevel.title = moduleName;
                            firstLevel.children = [];
                            map.set(moduleName, firstLevel);
                        }
                        firstLevel.children.push({
                            key: voucherCode,
                            title: name
                        });
                    });
                    this.treeMenu = [...map.values()];

                    console.log(this.treeMenu)
                }
            }).catch(error => { });
        },
        clickShrink () {
            setTimeout(() => {
                this.menuStyleStatus = !this.menuStyleStatus;
                if (this.menuStyleStatus) {
                    this.menuStyle = { 'flex': '0 0 250px', 'width': '250px', 'border-right': '1px solid #ccc' }
                    this.munuTreeStyle = { 'display': 'block' }
                } else {
                    this.menuStyle = { 'flex': '0 0 32px', 'width': '32px', 'border': 'none' }
                    this.munuTreeStyle = { 'display': 'none' }
                }
            }, 200)
        },
        treeTieleFun (data) {
            data.forEach(item => {
                item.title = item.name;
                if (item.children && item.children.length > 0) {
                    this.treeTieleFun(item.children);
                }
            });
        },
        //获取可编辑的列名
        editColumnArray () {
            let editcloumn = [];
            this.columnsModal.forEach((item, index) => {
                editcloumn.push(item.dataIndex);
            });
            this.editColumn = editcloumn;
        },
        rowClassName (record, index) {
            return this.mouseIndex == index ? 'hoverRowStyl' : '';
        },
        onSelect (keys, rows) {
            console.log('树形菜单选中', keys, rows, rows.node.dataRef);
            if (rows.selected && keys.indexOf('-') == -1) {
                this.selectedTreeKeys = keys;
                this.voucherType = rows.node.dataRef.key;
                this.voucherTypeName = rows.node.dataRef.title;
            } else {
                this.selectedTreeKeys = [];
                this.voucherType = null;
                this.voucherTypeName = null;
            }
            this.getDataList()
        },
        cancel () {
            this.templateModal = false;
        },
        onSelectChange (keys, rows) {
            console.log(keys, rows);
            this.selectedKeys = keys;
            this.selectedRows = rows;
        },
        templateSave () {
            if (this.vclassId == null) {
                this.$message.warning('请选择凭证字');
                return;
            }
            let requestData = {
                code: this.code,
                name: this.templateName,
                word: this.word,
                isDefault: this.isDefault,
                remarks: this.remarks,
                voucherType: this.voucherType,
                voucherTypeName: this.voucherTypeName,
                vclassId: this.vclassId,
                vclassName: this.vclassName,
                id: this.nowId,
                voucherTemplateDetailList: this.dataSourceModal.filter(res => res.accountingType != null),
            }
            save(requestData).then(res => {
                if (res.code === 200) {
                    this.$message.success('保存成功');
                    this.templateModal = false;
                    this.selectedKeys = [];
                    this.selectedRows = [];
                    this.getDataList();
                }
            })
        },
        templateEdit (type) {
            //新增 || 修改 模板
            this.editStatus = type;
            if (type == 1) {
                if (!this.voucherType) {
                    this.$message.warning('请先选择模板单据');
                    return
                }
                //新增
                this.templateModal = true;
                this.nowId = null;
                this.code = null;
                this.templateName = null;
                this.word = null;
                this.isDefault = 0;
                this.remarks = null;
                this.vclassId = null;
                this.vclassName = null;
                this.dataSourceModal = [];

                this.selectedKeys = [];
                this.selectedRows = [];
                this.complementTable();//补齐表格
            } else {
                //修改
                if (this.selectedKeys.length != 1) {
                    this.$message.warning('请选择一条数据');
                    return
                }
                let backData = _.cloneDeep(this.selectedRows[0]);
                this.nowId = backData.id;
                this.code = backData.code;
                this.templateName = backData.name;
                this.word = backData.word;
                this.isDefault = backData.isDefault;
                this.remarks = backData.remarks;
                this.vclassId = backData.vclassId;
                this.vclassName = backData.vclassName;
                this.voucherType = backData.voucherType;
                this.voucherTypeName = backData.voucherTypeName;
                this.dataSourceModal = backData.voucherTemplateDetailList;

                this.templateModal = true;
                this.complementTable();//补齐表格
            }
        },
        templateDelete () {
            //删除
            if (this.selectedKeys.length != 1) {
                this.$message.warning('请选择一行删除');
                return;
            }
            let that = this;
            this.$confirm(
                {
                    title: '提示',
                    content: <span>是否确认删除模板?</span>,
                    okText: '确定',
                    cancelText: '取消',
                    onOk () {
                        remove({ id: that.selectedRows[0].id }).then(res => {
                            if (res.code === 200) {
                                that.$message.success('删除成功');
                                that.getDataList('search');
                                that.nowId = null;
                                that.selectedKeys = [];
                                that.selectedRows = [];
                            }
                        })
                    },
                    onCancel () {

                    },
                }
            )
        },
        //改变分页大小
        changePageSize (e) {
            const value = e.target.value;
            let size = Number.parseInt(value);
            if (!size) {
                size = 20;
            }
            if (size > 500) {
                size = 500;
            }
            const { pagination } = this;

            Object.assign(this.pagination, {
                current: 1,
                pageSize: size,
            });
            this.getDataList();
        },
        getDataList (t) {
            //获取列表
            if (t == 'search') {
                this.pagination.current = 1;
            }
            let data = {
                current: this.pagination.current,
                size: this.pagination.pageSize,
                voucherType: this.voucherType,
            };
            this.isRun = true;
            getList(data).then(res => {
                if (res.code === 200) {
                    const { records, total, current, size } = res.data;
                    this.isRun = false;
                    this.pagination.total = total;
                    this.pagination.current = current;
                    this.pagination.pageSize = size;
                    this.dataSource = records;
                }
            })
        },
        searchBackData (record) {
            console.log(record);
            if (record && record.name) {
                this.word = record.classWord;
                this.vclassId = record.id;
                this.vclassName = record.name;
            }
        },
        onCellChange (indexTable, dataIndex, value) {
            console.log('当前点击的数据：', value);
            const dataSourceModal = [...this.dataSourceModal];
            const target = dataSourceModal.find((item, index) => index === indexTable);
            if (dataIndex == 'accountingName') {
                if (value) {
                    target['accountingName'] = value.treeNames.split('/').join('-');
                    target['accountingId'] = value.id;
                    target['accountingCode'] = value.code;
                    target['accountingRemark'] = value;
                } else {
                    target['accountingName'] = null;
                    target['accountingCode'] = null;
                    target['accountingId'] = null;
                    target['accountingRemark'] = null;
                }
            } else if (dataIndex == 'accountingType') {
                //科目来源
                if (value == 1) {
                    target['accountingName'] = null;
                    target['accountingId'] = null;
                    target['accountingCode'] = value.code;
                }
                target[dataIndex] = value;
            } else if (dataIndex == 'debitAmount') {

                target[dataIndex] = value;
                if (value) {
                    target['creditAmount'] = null;
                }
            } else if (dataIndex == 'creditAmount') {
                //贷方金额
                target[dataIndex] = value;
                if (value) {
                    target['debitAmount'] = null;
                }
            } else {
                target[dataIndex] = value;
            }

            this.$nextTick(() => {
                this.dataSourceModal = dataSourceModal;
                this.reload();
            })


        },




        // 拖动
        drag () {
            // 首先获取需要拖拽的dom节点
            const el1 = document.querySelectorAll('.filed-table .ant-table-tbody')[0];
            if (!el1) return false;
            this.isDrag = true;
            Sortable.create(el1, {
                disabled: false, // 是否开启拖拽
                ghostClass: 'sortable-ghost', //拖拽样式
                animation: 150, // 拖拽延时，效果更好看
                group: { // 是否开启跨表拖拽
                    pull: false,
                    put: false
                },
                onEnd: (e) => { // 这里主要进行数据的处理，拖拽实际并不会改变绑定数据的顺序，这里需要自己做数据的顺序更改
                    let arr = this.filedData; // 获取表数据

                    let removeItem = arr.splice(e.oldIndex, 1)[0];
                    console.log(removeItem)
                    console.log(e)

                    arr.splice(e.newIndex, 0, removeItem); // 数据处理
                    //提前 赋值一个带值的数组（BUG 修复）
                    this.filedData = [{}];
                    this.$nextTick(function () {
                        this.filedData = [...arr];
                        this.filedData.map((item, index) => {
                            item.sort = index + 1;
                            // item.isEdit = true;
                        });
                    });
                }
            });
        },
        syncFun () {
            this.getDataList();
        },
    },
};
</script>
<style lang="less">
    @import '~@/style/purchase/voucher.less';
    .content-demand-wrapper {
        height: calc(100% - 42px);
        // overflow-y: auto;
        display: flex;
        .content-menu {
            position: relative;
            transition: all 0.2s;
            flex: 0 0 250px;
            padding: 10px 0px;
            height: 100%;
            border-right: 1px solid #ccc;
            .shrink-btn {
                position: absolute;
                right: 0;
                top: 50%;
                width: 32px;
                height: 40px;
                line-height: 35px;
                text-align: center;
                cursor: pointer;
                z-index: 888;
            }
            .menu-tree-box {
                position: relative;
                height: 100%;
                overflow-y: auto;
            }
            .menu-btn-box {
                height: 33px;
                position: absolute;
                width: 100%;
                border-bottom: 1px solid #ccc;
                right: 0px;
                top: 0px;
                text-align: right;
            }
        }
        .content-view {
            margin: 0px;
            flex: 1;
            // height: calc(100% - 42px);
            height: 100%;
            .template-list-box {
                padding: 10px;
                height: 100%;
            }
        }
        .edit-box {
            width: 900px;
            height: calc(100% - 60px);
            overflow-y: auto;
            padding: 10px;
        }
    }
    .demand-modal {
        label:not(.form-check-label):not(.custom-file-label) {
            font-weight: normal;
        }
        .ant-form-item {
            margin-bottom: 0px;
        }
    }
    .finance-template-box-header {
        display: flex;
        justify-content: space-around;
        .ant-select-selection,
        .ant-input {
            border: none;
            border-bottom: 1px solid #a0a0a0;
            border-radius: 0;
        }
        .ant-select-selection:focus,
        .ant-input:focus {
            box-shadow: none;
        }
        .filter {
            display: table;
            width: 246px;
            margin-bottom: 5px;
            .filter-label {
                display: table-cell;
                font-weight: normal;
                max-width: 160px;
                line-height: 32px;
                white-space: nowrap;
                vertical-align: bottom;
                text-overflow: ellipsis;
                overflow: hidden;
            }
            .filter-control {
                display: table-cell;
                width: 100%;
            }
        }
    }
</style>
